import cv2;
import mediapipe as mp;
import time;

# 获取相机
capture = cv2.VideoCapture(0);

mpHands = mp.solutions.hands; # 手部侦测模型

hands = mpHands.Hands(); # 手部侦测基类
mpDraw = mp.solutions.drawing_utils; # 绘画
# 设置点的样式
handLmSpec = mpDraw.DrawingSpec(color=(0,0,255),thickness=5);
# 设置线的样式
handConSpec = mpDraw.DrawingSpec(color=(0,255,0),thickness=10);

pTime = 0;
cTime = 0;

while True:
    ret , frame = capture.read();

    if ret:
        # 将frame由bgr -> rgb
        img = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB);
        # 进行处理
        result = hands.process(img);
        # 获取视图窗口的宽度和高度
        frameHeight = frame.shape[0];
        frameWidth = frame.shape[1];
        # 标记每一个关键点(共21个)
        if result.multi_hand_landmarks:
            for handLandmarks in result.multi_hand_landmarks:
                # 标记点的位置
                mpDraw.draw_landmarks(frame,handLandmarks,mpHands.HAND_CONNECTIONS,handLmSpec,handConSpec);
                # 获取每一个关键点的坐标
                for i , landmark in enumerate(handLandmarks.landmark):
                    xPos = int(landmark.x * frameWidth);
                    yPos = int(landmark.y * frameHeight);
                    # 标记点的名称
                    cv2.putText(frame,str(i),(xPos-25,yPos+5),cv2.FONT_HERSHEY_SIMPLEX,0.4,(0,0,255),2);
                    print(i,xPos,yPos);

        # FPS的显示
        cTime = time.time();
        fps = 1/(cTime-pTime);
        pTime = cTime;
        cv2.putText(frame,f"FPS {int(fps)}",(30,50),cv2.FONT_HERSHEY_SIMPLEX,1,(255,0,0),3);

        # 显示每一帧
        cv2.imshow("Frame",frame);

    # q键退出
    if cv2.waitKey(1) == ord('q'):
        break;